package org.sunyaxing.transflow.transflowapp.plugins.filters;

import com.alibaba.fastjson2.JSONObject;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sunyaxing.transflow.api.TransData;
import org.sunyaxing.transflow.api.common.Handle;
import org.sunyaxing.transflow.api.common.ano.Extension;
import org.sunyaxing.transflow.api.common.ano.HandleItem;
import org.sunyaxing.transflow.api.common.ano.ScopeContentCheck;
import org.sunyaxing.transflow.api.extensions.base.ExtensionContext;
import org.sunyaxing.transflow.api.extensions.base.typesimpl.TransFlowMiddleJsonGatewayHandler;
import org.sunyaxing.transflow.transflowapp.controllers.JobLogsWs;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Function;

@Extension("plugin-json-gateway")
@ScopeContentCheck(
        handle = @HandleItem(field = "config", label = "脚本", required = true, type = "code", defaultValue = "")
)
public class ScriptGatewayExt extends TransFlowMiddleJsonGatewayHandler {
    private static final Logger log = LoggerFactory.getLogger(ScriptGatewayExt.class);

    public ScriptGatewayExt(ExtensionContext extensionContext) {
        super(extensionContext);
    }

    @Override
    protected void afterInitHandler(JSONObject config, List<Handle> handles) {

    }

    @Override
    public Function<TransData<JSONObject>, Boolean> parseHandleToConsumer(String handleId, String handleValue) {
        GroovyShell groovyShell = new GroovyShell();
        Script script = groovyShell.parse(handleValue);
        log.info("编译完成 \n {}", script);
        ReentrantLock reentrantLock = new ReentrantLock();
        return transData -> {
            JSONObject jsonObject = transData.getData();
            reentrantLock.lock();
            Object result = null;
            try {
                script.setProperty("data", jsonObject);
                result = script.run();
                JobLogsWs.sendMessage(jobId, "【{}】gateway 处理结果 {}", extensionContext.getNodeName(), result);
                JobLogsWs.sendMessage(jobId, "【{}】发送数据 {}", extensionContext.getNodeName(), jsonObject.toJSONString());
            } finally {
                reentrantLock.unlock();
            }
            return result instanceof Boolean && Boolean.TRUE.equals(result);
        };
    }


    @Override
    public void destroy() {

    }
}
